package com.unionftech.common.utils

import android.content.Context
import com.unionftech.common.widget.ui.ChangeDevActivity

object ChangeDevUtil {
    /**
     * 需要连续点击8次
     */
    private const val CLICK_THRESHOLD = 8

    /**
     * 连续点击5次是开始提醒还剩多少点击次数
     */
    private const val CLiCK_TIPS_THRESHOLD = 5

    /**
     * 两次点击间隔不超过1s
     */
    private const val CLICK_INTERVAL = 1000
    private var clickCount = 0
    private var lastClickTime = 0L
    private lateinit var changeUrlList: MutableList<String>


    @JvmStatic
    fun initChangeBaseUrlList(map: Map<String, String>) {
        if (::changeUrlList.isInitialized) {
            return
        }
        changeUrlList = mutableListOf()
        for (entry in map.entries) {
            changeUrlList.add("${entry.key}\n${entry.value}")
        }
    }

    @JvmStatic
    fun changeDev(context: Context) {
        if (!::changeUrlList.isInitialized) {
            return
        }
        val currentTime = System.currentTimeMillis()
        if (currentTime - lastClickTime < CLICK_INTERVAL) {
            clickCount++
        } else {
            //超过间隔时间，重置计数
            clickCount = 1
        }
        lastClickTime = currentTime
        if (clickCount in CLiCK_TIPS_THRESHOLD..<CLICK_THRESHOLD) {
            ToastUtils.shortToast("还需点击${CLICK_THRESHOLD - clickCount}次，开启环境切换")
        }
        if (clickCount >= CLICK_THRESHOLD) {
            toggleBaseUrl(context)
            //重置计数
            clickCount = 0
        }
    }


    private fun toggleBaseUrl(context: Context) {
        if (::changeUrlList.isInitialized) {
            ChangeDevActivity.startThis(context, changeUrlList)
        } else {
            ToastUtils.longToast("请先设置可切换域名的数据集")
        }
    }
}